import { Card, Tree } from 'antd';
import React, { useEffect, useState } from 'react';
import Rightbuildings from '../components/Rightbuildings';
import { DataNode } from 'antd/es/tree';
import { getBuildingsList } from '../request';
import { useIntl } from '@umijs/max';

const LayerCard: React.FC = () => {
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>(['']);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>(['']);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const [list, setList] = useState<DataNode[]>([]);
  const [Bon, setBon] = useState<any>([]);
  const [Bonlist, setBonlist] = useState<any>([]);
  const [getfloor, setgetfloor] = useState();
  const intl = useIntl()
  const getlist = async () => {
    const buildlist = await getBuildingsList();
    if (!buildlist.data.list) return false;
    const newBon = buildlist.data.list.map(
      (item: { bno: React.SetStateAction<undefined> }) => item.bno,
    );
    setBon(newBon);
    const treeData = buildlist.data.list.map(
      (item: { bno: string; id: { toString: () => string }; floor: string }) => ({
       title: `${item.bno} ${intl.formatMessage({id:"card.building"})}`,
         key: `${item.bno}${intl.formatMessage({id:"card.building"})}-${item.bno.toString()}`,
        children: item.floor.split(',').map((floor, index) => ({
          title: floor,
          key: `${parseInt(item.bno)}-${parseInt(floor)}`,
        })),
      }),
    );
    setList(treeData);
  };
  useEffect(() => {
    getlist();
  }, []);

  const onExpand = (expandedKeysValue: React.Key[]) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };
  function padZero(num: string) {
    var str = num.toString();
    var len = str.length;
    if (len < 2) {
      return '0' + str;
    } else {
      return str;
    }
  }

  const onCheck = (checkedKeysValue: any) => {
    console.log(checkedKeysValue);
    const result = checkedKeysValue
      .map((item: any) => {
        const [building, floor] = item.split('-');
        return `${building}栋${floor}层`;
      })
      .filter((v: any) => !v.includes('栋栋'))
      .join(',');
    let resAAA = '';
    let resBBB = '';
    let resCCC = '';
    checkedKeysValue.map((item: string) => {
      let str = item.split('-');
      resAAA += str[0] + '栋,';
      resBBB += str[1] + '层,';
      resCCC = resBBB.replace('栋', '');
    });

    let res3 = {
      bon: [...new Set(resAAA.split(','))].join(','),
      floor: result,
    };
    setgetfloor(res3);
    let arr: any[] = [];
    let arr2: any[] | ((prevState: never[]) => never[]) = [];
    checkedKeysValue.map((item: string) => {
      let bon = item.split('-')[0];
      let foor = item.split('-')[1];
      let num1 = parseInt(bon).toString(16).toUpperCase().padStart(2, '0');
      let num2 = padZero(foor);
      let num3 = parseInt(num2).toString(16).toUpperCase();
      let num4 = padZero(num3);
      let str = `${num1}${num4}0000`;
      arr.push(str);
    });

    arr2 = arr.filter((item) => /^[0-9A-Za-z]+$/.test(item));
    setBonlist([...new Set(arr2)]);
    setCheckedKeys(checkedKeysValue);
  };

  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    console.log('onSelect', info);
    setSelectedKeys(selectedKeysValue);
  };
  const div = (
    <div>
      {intl.formatMessage({ id: 'card.Layer control card' })}{' '}
      <div
        style={{
          fontSize: '14px',
          backgroundColor: '#F5F5F5',
          fontWeight: '200',
          margin: '10px 0 10px 0',
        }}
      >
      {intl.formatMessage({ id: 'ManageCards.Layer control card' })}
      </div>
    </div>
  );

  return (
    <Card
      title={div}
      style={{ height: '100%' }}
      headStyle={{
        backgroundColor: '#F5F5F5',
      }}
    >
      <div>
        <div style={{ float: 'left' }}>
          <Tree
            checkable
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            onCheck={onCheck}
            checkedKeys={checkedKeys}
            onSelect={onSelect}
            selectedKeys={selectedKeys}
            treeData={list}
          />
        </div>
        <div style={{ float: 'left', marginLeft: '50px' }}>
          <Rightbuildings msg={`层控卡`} Bonlist={Bonlist} getfloor={getfloor} />
        </div>
      </div>
    </Card>
  );
};

export default LayerCard;
